package com.ews.onlineexchange.rest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;

import javax.activation.MimetypesFileTypeMap;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.ews.onlineexchange.dao.SimpleEntityManagerDao;
import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.model.Image;
import com.ews.onlineexchange.util.AttachmentUtils;
import com.ews.onlineexchange.util.Config;

import net.sf.json.JSONObject;

@Path(value = "/download")
public class DownloadRest {
	
	@Inject
	Config config;
	@Inject
	AttachmentUtils util;
	@Inject
	private SimpleEntityManagerDao dao;
	@GET
	@Path("/attachment/{attachmentId}")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadFile(@PathParam("attachmentId") String attachmentId) throws Exception {
	    Attachment attr = dao.find(Attachment.class, attachmentId);
	    String fileName = attr.getFilename();
	    String fullPath = util.getFullPath(attr);
	    File file = new File(fullPath);
	    ResponseBuilder response = Response.ok((Object) file);
	    response.header("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
	    return response.build();
	}
	
	@GET
	@Path("/image/{imageId}")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response getImage(@PathParam("imageId") String imageId) throws Exception {
	    Image image = dao.find(Image.class, imageId);
	    String filePath = config.getProperty("com.ews.onlineExchange.saveDir")+image.getFilepath();
	    byte[] data = AttachmentUtils.getBytes(filePath);
	    return Response.ok(new ByteArrayInputStream(data)).build();
	}
	
	@GET
	@Path("/attachmentToByte/{attachmentId}")
	@Produces("text/html; charset=UTF-8")
	public byte[] downloadFileToByte(@PathParam("attachmentId") String attachmentId) throws Exception {
	    Attachment attr = dao.find(Attachment.class, attachmentId);
	    String fileName = attr.getFilename();
	    String filePath = config.getProperty("com.ews.onlineExchange.saveDir")+attr.getFilepath();
	    byte[] data = AttachmentUtils.getBytes(filePath);
	    String type = new MimetypesFileTypeMap().getContentType(fileName);
	    System.out.println(type);
	    return data;
	}
	

	@GET
	@Path("/app/{fileName}")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadApp(@PathParam("fileName") String fileName) throws Exception {
	   String filePath = "d://hhsjzApp/"+fileName;
	    File file = new File(filePath);
	    ResponseBuilder response = Response.ok((Object) file);
	    response.header("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
	    return response.build();
	}
	

	@GET
	@Path("/getAppVersion")
	@Produces("application/json")
	public JSONObject getAppVersion_supplier() throws Exception {
		//这种方式只有在build path sources 中添加了以后才能读取到
//		URL url = this.getClass().getResource("/app/version_supplier.json");
//		File file = new File(url.getFile());
	   String filePath = "d://hhsjzApp/version_supplier.json";
	    String jsonStr = "";
    	try {
    		File jsonFile = new File(filePath);
    		FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
           JSONObject josnObj = JSONObject.fromObject(jsonStr);
           return josnObj;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@GET
	@Path("/getProfessionAppVersion")
	@Produces("application/json")
	public JSONObject getAppVersion_profession() throws Exception {
	   String filePath = "d://hhsjzApp/version_profession.json";
	    String jsonStr = "";
    	try {
    		File jsonFile = new File(filePath);
    		FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
           JSONObject josnObj = JSONObject.fromObject(jsonStr);
           return josnObj;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@POST
	@Path("/updateAppVersion/{versionNum}")
	@Produces("application/json")
	public JSONObject updateAppVersion(@PathParam("versionNum") String versionNum) throws Exception {
	   String filePath = "d://hhsjzApp/version_supplier.json";
	    String jsonStr = "";
	    JSONObject jsonObj = null;
    	try {
    		File jsonFile = new File(filePath);
    		FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
           jsonObj = JSONObject.fromObject(jsonStr);
           jsonObj.put("version", versionNum);
           FileWriter fw = new FileWriter(filePath);  
           PrintWriter out = new PrintWriter(fw);  
           out.write(jsonObj.toString());  
           out.println();  
           fw.close();  
           out.close(); 
           jsonObj = new JSONObject();
           jsonObj.put("status", 200);
           jsonObj.put("msg", "更新中介版本号成功！");
           
		} catch (IOException e) {
			e.printStackTrace();
			jsonObj = new JSONObject();
			jsonObj.put("status", 500);
	        jsonObj.put("msg", "更新中介版本号出错！");
		}
    	return jsonObj;
	}
	
	@POST
	@Path("/updateProfessionAppVersion/{versionNum}")
	@Produces("application/json")
	public JSONObject updateProfessionAppVersion(@PathParam("versionNum") String versionNum) throws Exception {
	   String filePath = "d://hhsjzApp/version_profession.json";
	    String jsonStr = "";
	    JSONObject jsonObj = null;
    	try {
    		File jsonFile = new File(filePath);
    		FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
           jsonObj = JSONObject.fromObject(jsonStr);
           jsonObj.put("version", versionNum);
           FileWriter fw = new FileWriter(filePath);  
           PrintWriter out = new PrintWriter(fw);  
           out.write(jsonObj.toString());  
           out.println();  
           fw.close();  
           out.close(); 
           jsonObj = new JSONObject();
           jsonObj.put("status", 200);
           jsonObj.put("msg", "更新审核组版本号成功！");
           
		} catch (IOException e) {
			e.printStackTrace();
			jsonObj = new JSONObject();
			jsonObj.put("status", 500);
	        jsonObj.put("msg", "更新审核组版本号出错！");
		}
    	return jsonObj;
	}
}
